import { Row, Col, Card, DatePicker, Button } from 'antd';
import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import StatisticsCard from '@/components/StatisticsCard/Index';
import { Area, Line, DualAxes } from '@ant-design/charts';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import { 
  getShopBoardData,
  getShopOrderData
 } from '@/services/shop/api';
import { currentDate, formatDate, formatMoney, getDateValue, MsgType, showMsg, subtractDays } from '@/utils/utils';
import { history } from 'umi';

const Index: React.FC = () => {
  // 图表数据
  const [data, setData] = useState([]);

  const [transformData, setTransformData] = useState([]);

  // 店铺看板数据
  const [boardData, setBoardData] = useState<any>({});
  // 店铺订单数据
  const [shopOrderData, setShopOrderData] = useState<any>({});

  const [startDate, setStartDate] = useState<string>(formatDate(subtractDays(7).format('YYYY-MM-DD'), 'YYYY-MM-DD'));
  const [endDate, setEndDate] = useState<string>(formatDate(currentDate().format('YYYY-MM-DD'), 'YYYY-MM-DD'));

  const [dateStart] = useState(subtractDays(7))
  const [dateEnd] = useState(currentDate())

  var categoryMap = {
    'total': '开单数',
    'totalPayNum': '支付单数',
    'totalPayPrice': '支付金额',
    'totalPrice': '开单金额',
    'totalRefundNum': '退款单数',
    'totalRefundPrice': '退款金额'
  }

  var config = {
    data: [data, transformData],
    xField: 'createDate',
    yField: ['count', 'price'],
    geometryOptions: [
      {
        geometry: 'line',
        seriesField: 'name',
        lineStyle: function lineStyle() {
          return { opacity: 0.5 };
        },
      },
      {
        geometry: 'column',
        isGroup: true,
        seriesField: 'type',
        columnWidthRatio: 0.4,
      }
    ]
  };

  const fetchBoardData = async () => {
    try {
      const data = await getShopBoardData();
      setBoardData(data);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  const fetchShopOrderData = async (params: any) => {
    try {
      const data = await getShopOrderData(params);
      setShopOrderData(data);
      handleChartsData(data.record_list);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  const handleChartsData = (list: any[]) => {
    const dataList: any[] = [];
    const transformDataList: any[] = [];

    list.forEach(item => {
      const createDate = item.createDate;
      for (const prop in item) {
        if (prop === 'createDate') {
          continue;
        }

        if (prop.indexOf('Price') > -1) {
          const dataItem = {
            createDate: createDate,
            price: item[prop],
            type: categoryMap[prop]
          }
          transformDataList.push(dataItem);
          transformDataList.sort((a, b) => {
            return Number(a.price) - Number(b.price)
          })
        } else {
          const dataItem = {
            createDate: createDate,
            count: item[prop],
            name: categoryMap[prop]
          }
          dataList.push(dataItem);
        }
      }
    })
    console.log(dataList)
    console.log(transformDataList)
    setData(dataList);
    setTransformData(transformDataList);
  }

  const onSearch = () => {
    if (startDate && endDate) {
      if (getDateValue(endDate) < getDateValue(startDate)) {
        showMsg('结束时间不能早于开始时间', MsgType.INFO);
        return;
      }
    }

    fetchShopOrderData({
      begin_date: formatDate(startDate, 'YYYYMMDD'),
      end_date: formatDate(endDate, 'YYYYMMDD')
    });
  }

  const navigateTo = (url: string, params: any) => {
    history.push({
      pathname: url,
      query: {
        ...params
      }
    })
  }

  useEffect(() => {
    fetchBoardData();
    onSearch();
  }, []);

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <div className="board-container">
        <div style={{marginBottom: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
          <StatisticsCard iconType="database" title="今日订单总数" number={boardData.todayOrderNum}/>
          <StatisticsCard title="今日销售总额" number={formatMoney(boardData.todayOrderPrice)} />
          <StatisticsCard title="昨日销售总额" number={formatMoney(boardData.yeOrderPrice)}/>
          <StatisticsCard style={{marginRight: 0}} title="近7日销售总额" number={formatMoney(boardData.dayOrderPrice)}/>
        </div>

        <Card title="待处理事务" style={{marginBottom: 15}}>
          <div className="card-inner">
            <div className="card-content">
              <div className="block-card">
                <div className="block-card-content">
                  <div className="block-card-item" onClick={() => {
                    navigateTo('/shop/order', { order_status: 'T'});
                   }}>
                    <span>待付款订单</span>
                    <span className="danger">({boardData.waitPayOrderNum})</span>
                  </div>
                  <div className="block-card-item" onClick={() => {
                    navigateTo('/shop/order', { order_status: 'P'});
                   }}>
                    <span>待发货订单</span>
                    <span className="danger">({boardData.waitSendOrderNum})</span>
                  </div>
                  <div className="block-card-item" onClick={() => {
                    navigateTo('/shop/order', { order_status: 'S'});
                   }}>
                    <span>已发货订单</span>
                    <span className="danger">({boardData.sendOrderNum})</span>
                  </div>
                </div>
              </div>
              <div className="block-card">
                <div className="block-card-content">
                  <div className="block-card-item" onClick={() => {
                    navigateTo('/shop/after-sale', { way: '2', apply_status: 'U'});
                   }}>
                    <span>待处理退款订单</span>
                    <span className="danger">({boardData.waitRefundNum})</span>
                  </div>
                  <div className="block-card-item" onClick={() => {
                    navigateTo('/shop/after-sale', { way: '1', apply_status: 'U'});
                   }}>
                    <span>待处理退货订单</span>
                    <span className="danger">({boardData.waitRefundGoodsNum})</span>
                  </div>
                </div>
              </div>
              <div className="block-card">
                <div className="block-card-content">
                  <div className="block-card-item" onClick={() => {
                    navigateTo('/shop/evaluate', {});
                   }}>
                    <span>待审核评价</span>
                    <span className="danger">({boardData.waitExamNum})</span>
                  </div>
                  <div className="block-card-item" onClick={() => {
                    navigateTo('/shop/consulting', {});
                   }}>
                    <span>待处理咨询信息</span>
                    <span className="danger">({boardData.waitConsultNum})</span>
                  </div>
                  <div className="block-card-item" onClick={() => {
                    navigateTo('/shop/complaint', {});
                   }}>
                    <span>待处理投诉信息</span>
                    <span className="danger">({boardData.waitStateNum})</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Card>

        <Row gutter={16}>
          <Col span={11}>
            <Card title="商品总览" style={{marginBottom: 15}}>
              <div className="card-inner goods-overview">
                <div className="card-content">
                  <div className="block-card">
                    <div className="block-card-content">
                      <div style={{flexDirection: 'column'}} className="block-card-item" onClick={() => {
                        navigateTo('/shop/goods', {goods_status: 'O'});
                      }}>
                        <span className="highlight">{boardData.onlineGoodsNum}</span>
                        <span>已上架</span>
                      </div>
                      <div style={{flexDirection: 'column'}} className="block-card-item" onClick={() => {
                        navigateTo('/shop/goods', {goods_status: 'D'});
                      }}>
                        <span className="highlight">{boardData.downGoodsNum}</span>
                        <span>已下架</span>
                      </div>
                      <div style={{flexDirection: 'column'}} className="block-card-item" onClick={() => {
                        navigateTo('/shop/goods', {flag: '1'});
                      }}>
                        <span className="highlight">{boardData.warnGoodsNum}</span>
                        <span>库存紧张</span>
                      </div>
                      <div style={{flexDirection: 'column'}} className="block-card-item" onClick={() => {
                        navigateTo('/shop/goods', {});
                      }}>
                        <span className="highlight">{boardData.totalGodosNum}</span>
                        <span>全部商品</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          </Col>
          <Col span={2}/>
          <Col span={11}>
            <Card title="客户总览" style={{marginBottom: 15}}>
              <div className="card-inner goods-overview">
                <div className="card-content">
                  <div className="block-card">
                    <div className="block-card-content">
                      <div style={{flexDirection: 'column', cursor: 'text'}} className="block-card-item">
                        <span className="highlight">{boardData.todayUserNum}</span>
                        <span>今日新增</span>
                      </div>
                      <div style={{flexDirection: 'column', cursor: 'text'}} className="block-card-item">
                        <span className="highlight">{boardData.yeUserNum}</span>
                        <span>昨日新增</span>
                      </div>
                      <div style={{flexDirection: 'column', cursor: 'text'}} className="block-card-item">
                        <span className="highlight">{boardData.monthUserNum}</span>
                        <span>本月新增</span>
                      </div>
                      <div style={{flexDirection: 'column', cursor: 'text'}} className="block-card-item">
                        <span className="highlight">{boardData.totalUserNum}</span>
                        <span>总客户数</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
        
        <Card title="订单统计" style={{marginBottom: 15}}>
          <div className="card-inner">
            <div className="card-side">
              <div className="side-item">
                <div className="title">周期订单总数</div>
                <div className="num">{shopOrderData.totalOrderNum}</div>
              </div>
              <div className="side-item">
                <div className="title">周期订单总额</div>
                <div className="num">{formatMoney(shopOrderData.totalOrderPrice)}</div>
              </div>
              <div className="side-item">
                <div className="title">周期付款总额</div>
                <div className="num">{formatMoney(shopOrderData.totalPayPrice)}</div>
              </div>
              <div className="side-item">
                <div className="title">周期退款总额</div>
                <div className="num">{formatMoney(shopOrderData.totalRefundPrice)}</div>
              </div>
            </div>
            <div className="card-content">
              <div className="area-wrap">
                <div className="date">
                  <DatePicker defaultValue={dateStart} onChange={(date, dateString) => {
                   setStartDate(dateString);
                  }} name="startDate" style={{width: 150}} />
                  <span style={{padding: '0 10px'}}>-</span>
                  <DatePicker onChange={(date, dateString) => {
                    setEndDate(dateString);
                  }} name="endDate" defaultValue={dateEnd} style={{width: 150}} />
                  <Button onClick={onSearch} style={{marginLeft: 10}} type="primary">查询</Button>
                </div>
                <DualAxes className="area" {...config} />
              </div>
            </div>
          </div>
        </Card>

      </div>
    </PageContainer>
  );
};
export default Index;
